import React, {useEffect, useState} from 'react'
import {Button, Space, message, Select} from 'antd'
import type {ColumnsType} from 'antd/es/table'
import {history} from 'umi'
import {
	PlusOutlined,
	ArrowUpOutlined,
	ArrowDownOutlined,
} from '@ant-design/icons'
import styles from './index.less'
import SearchForm from '@/components/SearchForm'
import Permissions from '@/components/Permissions'
import Modal from '@/components/Modal'
import CustomTable from '@/components/Table'
import {
	deleteWarehousegoodsarchives,
	getErrorExcelList,
	getWarehousegoodsarchivesList,
	goodAccountImport,
} from '@/service/storage/material'
import BatchUpload from '@/components/BatchUpload'
import {modalApi} from '@/utils/modalReq'
import {getDict} from '@/service/common/dict'
import {downloadDocumentUrl} from '@/service/common/download'

interface DataType {
	id: string
	goodsCode: string
	goodsArchivesName: string
	archivesStatus: string
	company: string
	largeClassify: string
	middleClassify: string
	createTime: string
}

const formItemLayout = {
	labelCol: {flex: '120px'},
	wrapperCol: {flex: '1'},
}

const material = () => {
	const [dataSourse, setDataSourse] = useState<any[]>([])
	const [searchData, setSearchData] = useState({})
	const [isModalOpen, setIsModalOpen] = useState(false)
	const [id, setId] = useState<string>('')
	const [loading, setLoading] = useState(false)
	const [total, setTotal] = useState()
	const [params, setParams] = useState({
		current: 1,
		size: 10,
	})
	const [isUploadModalOpen, setIsUploadModalOpen] = useState(false)
	const [dictData, setDictData] = useState<any>({})

	useEffect(() => {
		getDict(
			{
				dictKeys: [
					'storage_large_classify',
					'storage_middle_classify',
					'Company',
				],
			},
			(res: any) => {
				setDictData(res)
			},
		)
	}, [])

	// 获取物料档案列表
	const getData = () => {
		setLoading(true)
		getWarehousegoodsarchivesList({...params, ...searchData})
			.then((res: any) => {
				if (res?.success) {
					setDataSourse(res?.data?.records)
					setTotal(res?.data?.total)
					setLoading(false)
				} else {
					setLoading(false)
				}
			})
			.catch((err) => {
				setDataSourse([])
				message.error(err)
				setLoading(false)
			})
	}
	useEffect(() => {
		getData()
	}, [params])

	/** 点击详情及编辑事件 */
	const onDetails = (type: string, record: DataType) => {
		history.push({
			pathname: `/storage/material/${type}`,
			query: {
				id: record?.id,
			},
		})
	}

	const columns: ColumnsType<DataType> = [
		{
			title: '代码',
			dataIndex: 'goodsCode',
			align: 'center',
			width: 150,
		},
		{
			title: '名称',
			dataIndex: 'goodsArchivesName',
			align: 'center',
			width: 100,
		},
		{
			title: '状态',
			dataIndex: 'archivesStatus',
			align: 'center',
			width: 100,
			render: (text) => <>{text === '1' ? '已启用' : '未启用'}</>,
		},
		{
			title: '大分类',
			dataIndex: 'largeClassify',
			align: 'center',
			width: 100,
			render: (text) => (
				<Select
					value={text}
					disabled
					allowClear
					fieldNames={{value: 'dictKey', label: 'dictValue'}}
					options={dictData?.storage_large_classify}
				/>
			),
		},
		{
			title: '中分类',
			dataIndex: 'middleClassify',
			align: 'center',
			width: 100,
			render: (text) => (
				<Select
					value={text}
					disabled
					allowClear
					fieldNames={{value: 'dictKey', label: 'dictValue'}}
					options={dictData?.storage_middle_classify}
				/>
			),
		},
		{
			title: '单位',
			dataIndex: 'company',
			align: 'center',
			width: 100,
			render: (text) => (
				<Select
					value={text}
					disabled
					allowClear
					fieldNames={{value: 'dictKey', label: 'dictValue'}}
					options={dictData?.Company}
				/>
			),
		},
		{
			title: '创建时间',
			dataIndex: 'createTime',
			align: 'center',
			width: 160,
		},
		{
			title: '操作',
			key: 'action',
			align: 'center',
			width: 120,
			render: (text: any, record) => (
				<Space size={12}>
					<Permissions permissionID="amc_storage_material_view">
						<Button
							type="link"
							onClick={() => {
								onDetails('view', record)
							}}>
							详情
						</Button>
					</Permissions>
					<Permissions permissionID="amc_storage_material_edit">
						<Button
							type="link"
							onClick={() => {
								onDetails('edit', record)
							}}>
							编辑
						</Button>
					</Permissions>
					{record.archivesStatus === '2' ? (
						<Permissions permissionID="amc_storage_material_delete">
							<Button
								type="link"
								onClick={() => {
									setId(record?.id)
									setIsModalOpen(true)
								}}>
								删除
							</Button>{' '}
						</Permissions>
					) : (
						''
					)}
				</Space>
			),
		},
	]
	const formItems: any[] = [
		{
			type: 'group',
			key: 'group1',
			groupItems: [
				{
					type: 'input',
					label: '物料代码/名称',
					name: 'keyWords',
					key: 'keyWords',
				},
				{
					type: 'select',
					key: 'archivesStatus',
					name: 'archivesStatus',
					label: '状态',
					keys: 'value',
					title: 'text',
					items: [
						{
							value: '1',
							text: '已启用',
						},
						{
							value: '2',
							text: '未启用',
						},
					],
				},
				{
					type: 'input',
					label: '大分类中分类',
					name: 'supplierCode',
					key: 'supplierCode',
				},
			],
		},
	]
	const onFinish = (values: any) => {
		setSearchData(values)
		setParams({
			current: 1,
			size: 10,
		})
	}

	const onReset = () => {
		setSearchData({})
		setParams({
			current: 1,
			size: 10,
		})
	}

	const deleteData = () => {
		deleteWarehousegoodsarchives(id)
			.then((res: any) => {
				if (res.success) {
					message.success(res.msg)
					setIsModalOpen(false)
					getData()
				}
			})
			.catch((err) => {
				message.error(err)
			})
	}
	const errorColumns: ColumnsType<DataType> = [
		{
			title: '物料名称',
			dataIndex: 'goodsArchivesName',
			align: 'center',
			width: 120,
		},
		{
			title: '大分类',
			dataIndex: 'largeClassify',
			align: 'center',
			width: 100,
		},
		{
			title: '中分类',
			dataIndex: 'middleClassify',
			align: 'center',
			width: 100,
		},
		{
			title: '失败原因',
			dataIndex: 'message',
			align: 'center',
			width: 200,
		},
	]

	return (
		<div className={styles.material}>
			<div className={styles.content}>
				<div className={styles.search}>
					<SearchForm
						onFinish={onFinish}
						onReset={onReset}
						formItems={formItems}
						formLayout={formItemLayout}
					/>
				</div>
				<div className={styles.btnlist}>
					<Space size={12}>
						<Permissions permissionID="amc_storage_material_add">
							<Button
								icon={<PlusOutlined />}
								type="primary"
								ghost
								size="small"
								onClick={() => {
									history.push('/storage/material/add')
								}}>
								新增数据
							</Button>
						</Permissions>
						<Permissions permissionID="amc_storage_material_import">
							<Button
								icon={<ArrowUpOutlined />}
								className={styles.warning}
								ghost
								size="small"
								onClick={() => {
									setIsUploadModalOpen(true)
								}}>
								导入
							</Button>
						</Permissions>
						<Permissions permissionID="amc_storage_material_export">
							<Button
								icon={<ArrowDownOutlined />}
								className={styles.import}
								ghost
								size="small"
								onClick={() => {
									downloadDocumentUrl({
										resourceId: '134',
										queryDesc:
											'物料档案导出,resourceId:134',
										queryParam: searchData,
									})
								}}>
								导出
							</Button>
						</Permissions>
					</Space>
				</div>
				<CustomTable
					params={params}
					columns={columns}
					total={total}
					pagination
					callback={(pagination: any) => {
						setParams(pagination)
					}}
					loading={loading}
					dataSource={dataSourse}
				/>
			</div>
			<Modal
				text="确认要删除该数据吗？"
				onSubmit={deleteData}
				isModalOpen={isModalOpen}
				setIsModalOpen={setIsModalOpen}
			/>
			<BatchUpload
				isModalOpen={isUploadModalOpen}
				setIsModalOpen={setIsUploadModalOpen}
				importData={goodAccountImport}
				onTableList={getErrorExcelList}
				getListData={getData}
				fileNmae="excel"
				modular="material"
				type={1}
				saveType={2}
				downloadUrl="storage/物料档案.xlsx"
				uploadFileUrl={`${modalApi.storage}/warehousegoodsarchives/goodAccountImport`}
				columns={errorColumns}
				sourceId={23}
				templateType="物料档案"
			/>
		</div>
	)
}

export default material
